
<template>
  <page-meta :page-style="$theme.pageStyle">
    <!-- #ifndef H5 -->
    <navigation-bar :front-color="$theme.navColor" :background-color="$theme.navBgColor" />
    <!-- #endif -->
  </page-meta>
  <view class="index" :style="pageStyle">
    <!-- 将 header 放置在固定位置 -->
    <view class="custom-header" :style="{ 'padding-top': statusBarHeight + 'px' }">
      <text class="header-text">资质</text>
    </view>
    <view class="custom-body" :style="{ 'margin-top': statusBarHeight + 'px' }">
      <u-form :model="model" :rules="rules" ref="formRef" label-width="300">
        <view class="card-title" :style="cardBackgroundStyle">身份信息</view>
        <view class="form-container">
          <u-form-item label="司机姓名" prop="name">
            <u-input
                class="right-placeholder"
                v-model="model.name"
                placeholder="请输入姓名"
            />
          </u-form-item>
          <u-form-item label="手机号" prop="phone">
            <u-input
                class="right-placeholder"
                v-model="model.phone"
                placeholder="请输入手机号"
            />
          </u-form-item>
          <u-form-item label="身份证号" prop="idCard">
            <u-input
                class="right-placeholder"
                v-model="model.idCard"
                placeholder="请输入身份证号"
            />
          </u-form-item>
        </view>
        <view class="card-title" :style="cardBackgroundStyle">车辆信息</view>
        <view class="form-container">
          <u-form-item label="车型" prop="carType">
            <u-input
                class="right-placeholder"
                v-model="model.carTypeLabel"
                type="select"
                placeholder="请选择车型"
                @click="select1.show = true"
            />
          </u-form-item>
          <u-form-item label="车牌号" prop="licensePlate">
            <u-input
                class="right-placeholder"
                v-model="model.licensePlate"
                placeholder="请输入车牌号"
            />
          </u-form-item>
          <u-form-item label="车架号" prop="frameNumber">
            <u-input
                class="right-placeholder"
                v-model="model.frameNumber"
                placeholder="请输入车架号"
            />
          </u-form-item>
          <u-form-item label="车辆图片" prop="carImage">
            <u-upload
                v-bind="uploadProps"
                @success="handleUploadSuccess('carImage', $event)"
            />
          </u-form-item>
          <u-form-item label="驾驶证图片" prop="driverLicenseImage">
            <u-upload
                v-bind="uploadProps"
                @success="handleUploadSuccess('driverLicenseImage', $event)"
            />
          </u-form-item>
          <u-form-item label="行驶证图片" prop="registrationImage">
            <u-upload
                v-bind="uploadProps"
                @success="handleUploadSuccess('registrationImage', $event)"
            />
          </u-form-item>
        </view>
        <u-button
            type="warning"
            shape="circle"
            class="submit-btn"
            @click="submitForm"
            :loading="submitting"
        >
          {{ submitting ? '提交中...' : '提交审核' }}
        </u-button>
      </u-form>
      <u-select
          v-model="select1.show"
          :list="carTypeList"
          :label-name="'name'"
          :value-name="'id'"
          :border="false"
          :placeholder="'请选择车型'"
          @confirm="handleCarTypeChange"
      />
    </view>
    <!-- 返回顶部按钮 -->
    <u-back-top
        :scroll-top="scrollTop"
        :top="100"
        :customStyle="{
                backgroundColor: '#FFF',
                color: '#000',
                boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)'
            }"
    >
    </u-back-top>

    <!--  #ifdef MP  -->
    <!--  微信小程序隐私弹窗  -->
    <MpPrivacyPopup></MpPrivacyPopup>
    <!--  #endif  -->

    <tabbar />
  </view>
</template>

<script setup lang="ts">import { getIndex } from '@/api/shop'
import { onLoad, onPageScroll } from '@dcloudio/uni-app'
import { computed, reactive, ref } from 'vue'
import { useAppStore } from '@/stores/app'
import { submitDriverInfo } from '@/api/user'
import { carTypeAll } from '@/api/car_type'
// #ifdef MP
import MpPrivacyPopup from './component/mp-privacy-popup.vue'
// #endif
import USelect from '@/uni_modules/vk-uview-ui/components/u-select/u-select.vue'

const uploadProps = {
  list: [],
  limit: 1,
  showUploadList: false,
  showRemove: false,
  showUploadIcon: false,
  showDeleteIcon: false,
  showPreviewIcon: false,
  showProgress: false,
  showReplaceIcon: false,
  header: {},
  formData: {},
  fileValidator(file) {
    const isValidSize = file.size <= 5 * 1024 * 1024
    const isValidType = /\.(jpg|jpeg|png|gif)$/i.test(file.name)
    if (!isValidSize) {
      uni.showToast({ title: '图片大小不能超过 5MB', icon: 'none' })
      return false
    }
    if (!isValidType) {
      uni.showToast({ title: '仅支持 JPG/PNG/GIF 格式', icon: 'none' })
      return false
    }
    return true
  },
  onError() {
    uni.showToast({ title: '图片上传出错', icon: 'none' })
  }
}

const state = reactive<{
  pages: any[]
  meta: any[]
}>({
  pages: [],
  meta: []
})

const model = reactive({
  name: '',
  phone: '',
  idCard: '',
  carType: null,
  licensePlate: '',
  frameNumber: '',
  carImage: '',
  driverLicenseImage: '',
  registrationImage: '',
  carTypeLabel: ''
})

const carTypeList = ref([])
const submitting = ref(false)

const getCarType = async () => {
  try {
    const data = await carTypeAll()
    carTypeList.value = data
    if (carTypeList.value.length > 0) {
      model.carType = carTypeList.value[0].id
      model.carTypeLabel = carTypeList.value[0].name
    }
  } catch (error) {
    uni.showToast({ title: '车型加载失败', icon: 'none' })
  }
}

const rules = reactive({
  name: [{ required: true, message: '请输入司机姓名' }],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确' }
  ],
  licensePlate: [{ required: true, message: '请输入车牌号' }],
  carType: [{ required: true, message: '请选择车型' }],
  frameNumber: [{ required: true, message: '请输入车架号' }],
  carImage: [{ required: true, message: '请上传车辆图片' }],
  driverLicenseImage: [{ required: true, message: '请上传驾驶证图片' }],
  registrationImage: [{ required: true, message: '请上传行驶证图片' }]
})

const formRef = ref()

const scrollTop = ref<number>(0)
const percent = ref<number>(0)
const statusBarHeight = ref<number>(0)

const select1 = reactive({
  show: false,
  current: {},
  list: []
})

const pageStyle = computed(() => {
  return { 'background-color': `#FFFFFF` }
})

const appStore = useAppStore()

const getData = async () => {
  try {
    const data = await getIndex()
    if (data && data?.page?.data && data?.page?.meta) {
      state.pages = JSON.parse(data.page.data)
      state.meta = JSON.parse(data.page.meta)
      uni.setNavigationBarTitle({
        title: state.meta[0]?.content?.title || '资质认证'
      })
    } else {
      uni.showToast({ title: '页面数据加载异常', icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: '页面数据加载失败', icon: 'none' })
  }
}

const cardBackgroundStyle = computed(() => {
  const bg = appStore.getStyleConfig.cardBg
  return {
    'background-image': `url(${bg})`,
    'background-repeat': 'no-repeat',
    'background-position': 'left',
    'background-size': '80px auto'
  }
})

onPageScroll((event: any) => {
  scrollTop.value = event.scrollTop
  const top = uni.upx2px(100)
  percent.value = event.scrollTop / top > 1 ? 1 : event.scrollTop / top
})

const handleUploadSuccess = (field: string, res: any) => {
  if (res.code === 0) {
    model[field] = res.url
  } else {
    uni.showToast({ title: '图片上传失败', icon: 'none' })
  }
}

const handleCarTypeChange = (value: any) => {
  const selected = value[0]
  model.carType = selected.id
  model.carTypeLabel = selected.name
  select1.current = selected
}

const submitForm = async () => {
  if (submitting.value) return

  try {
    submitting.value = true
    await formRef.value.validate()
    const res = await submitDriverInfo(model)
    uni.showToast({ title: '提交成功', icon: 'success' })
  } catch (error) {
    uni.showToast({ title: '请检查表单内容', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

onLoad(() => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight
    Promise.all([getData(), getCarType()])
  } catch (error) {
    uni.showToast({ title: '页面初始化失败', icon: 'none' })
  }
})
</script>

<style lang="scss" scoped>.index {
  position: relative;
  background-repeat: no-repeat;
  background-size: 100% auto;
  overflow: hidden;
  width: 100%;
  transition: all 1s;
  min-height: calc(100vh - env(safe-area-inset-bottom));
  margin-top: 44px;
}

.custom-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.header-text {
  font-size: 20px;
  text-align: center;
}

.custom-body {
  background: #f8f8f8;
  padding: 15px;
}

.card-title {
  font-size: 20px;
  font-weight: bold;
  height: 45px;
  background-size: auto;
}

.form-container {
  background-color: #ffffff;
  padding: 16px;
  border-radius: 8px;
  margin: 20rpx 0;
}

.submit-btn {
  background-color: #f9b85e;
  margin-bottom: 120rpx;
}

.right-placeholder {
  :deep(.u-input__input) {
    text-align: right;
  }
}
</style>